package com.sddnytsh.body_buildingsystem.components

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material.icons.filled.Bluetooth
import androidx.compose.material.icons.filled.LocationOn
import androidx.compose.material.icons.filled.DirectionsRun
import androidx.compose.material.icons.filled.Analytics
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.outlined.Favorite
import androidx.compose.material.icons.outlined.PlayArrow
import androidx.compose.material.icons.outlined.Schedule
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.Stop
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.sddnytsh.body_buildingsystem.R
import com.sddnytsh.body_buildingsystem.data.state.UserState
import com.sddnytsh.body_buildingsystem.network.ExerciseApiService
import com.sddnytsh.body_buildingsystem.topic.*
import com.sddnytsh.body_buildingsystem.services.HealthDataManager
import com.sddnytsh.body_buildingsystem.services.PermissionManager
import com.sddnytsh.body_buildingsystem.services.PermissionStatus
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.platform.LocalContext
import android.content.SharedPreferences
import java.text.SimpleDateFormat
import java.util.*
import kotlin.random.Random

@Composable
fun Page3() {
    val context = LocalContext.current
    val exerciseApiService = remember { ExerciseApiService() }
    
    // 华为健康数据服务
    val healthDataManager = remember { HealthDataManager(context) }
    val permissionManager = remember { PermissionManager(context) }
    
    // SharedPreferences用于持久化授权状态
    val sharedPrefs = remember { 
        context.getSharedPreferences("huawei_health_auth", android.content.Context.MODE_PRIVATE) 
    }
    
    // 健康数据状态
    val isInitialized by healthDataManager.isInitialized.collectAsState()
    val isAuthorized by healthDataManager.isAuthorized.collectAsState()
    val currentHeartRate by healthDataManager.currentHeartRate.collectAsState()
    val isDataAvailable by healthDataManager.isDataAvailable.collectAsState()
    
    // 权限和授权状态
    var showPermissionDialog by remember { mutableStateOf(false) }
    var showAuthorizationDialog by remember { mutableStateOf(false) }
    var permissionStatus by remember { mutableStateOf<PermissionStatus?>(null) }
    var isInitializing by remember { mutableStateOf(false) }
    var isRequestingAuth by remember { mutableStateOf(false) }
    
    // 防止重复弹出的状态
    var hasShownPermissionDialog by remember { mutableStateOf(false) }
    var hasShownAuthDialog by remember { mutableStateOf(false) }
    var hasInitialized by remember { mutableStateOf(false) }

    // 状态管理
    var showStartExerciseDialog by remember { mutableStateOf(false) }
    var showEndExerciseDialog by remember { mutableStateOf(false) }
    var selectedExercise by remember { mutableStateOf<ExerciseInfo?>(null) }
    var currentExerciseRecord by remember { mutableStateOf<ExerciseRecordInfo?>(null) }
    var exerciseRecords by remember { mutableStateOf<List<ExerciseRecordInfo>>(emptyList()) }

    // 数据状态
    var exerciseList by remember { mutableStateOf<List<ExerciseInfo>>(emptyList()) }
    var exerciseCategories by remember { mutableStateOf<List<String>>(emptyList()) }
    var selectedCategory by remember { mutableStateOf("全部分类") }
    var searchKeyword by remember { mutableStateOf("") }

    // 加载状态
    var isLoadingExercises by remember { mutableStateOf(false) }
    var isLoadingRecords by remember { mutableStateOf(false) }
    var isStartingExercise by remember { mutableStateOf(false) }
    var isEndingExercise by remember { mutableStateOf(false) }

    // 使用UserState中的用户ID
    val currentUserId = UserState.currentUserId ?: 1L
    val coroutineScope = rememberCoroutineScope()

    // 初始化数据
    LaunchedEffect(Unit) {
        // 防止重复初始化
        if (hasInitialized) return@LaunchedEffect
        hasInitialized = true
        
        // 检查权限状态
        permissionStatus = healthDataManager.checkPermissions()
        
        // 检查是否已经显示过权限对话框
        val hasShownPermissionBefore = sharedPrefs.getBoolean("has_shown_permission_dialog", false)
        
        // 如果权限未完全授予且未显示过权限对话框，显示权限对话框
        if (!permissionStatus!!.allGranted && !hasShownPermissionBefore) {
            sharedPrefs.edit().putBoolean("has_shown_permission_dialog", true).apply()
            showPermissionDialog = true
            return@LaunchedEffect
        }
        
        // 如果权限已授予，初始化华为健康数据服务
        if (permissionStatus!!.allGranted) {
            isInitializing = true
            val initialized = healthDataManager.initialize()
            isInitializing = false
            
            if (!initialized) {
                // 初始化失败，显示错误信息
                return@LaunchedEffect
            }
            
            // 检查是否已经显示过授权对话框
            val hasShownAuthBefore = sharedPrefs.getBoolean("has_shown_auth_dialog", false)
            
            // 如果未授权且未显示过授权对话框，显示授权对话框
            if (!isAuthorized && !hasShownAuthBefore) {
                sharedPrefs.edit().putBoolean("has_shown_auth_dialog", true).apply()
                showAuthorizationDialog = true
            }
        }
        
        // 加载运动分类
        loadExerciseCategories(exerciseApiService) { categories ->
            exerciseCategories = categories
        }
        loadExercises(exerciseApiService, selectedCategory, searchKeyword) { exercises ->
            exerciseList = exercises
        }
        loadExerciseRecords(exerciseApiService, currentUserId) { records ->
            exerciseRecords = records
        }
        checkCurrentExercise(exerciseApiService, currentUserId) { record ->
            currentExerciseRecord = record
        }
    }

    // 当分类或搜索关键词改变时重新加载运动列表
    LaunchedEffect(selectedCategory, searchKeyword) {
        loadExercises(exerciseApiService, selectedCategory, searchKeyword) { exercises ->
            exerciseList = exercises
        }
    }

    // 定义颜色
    val primaryColor = Color(0xFF4361EE) // 更柔和的蓝色
    val secondaryColor = Color(0xFF3A0CA3) // 深蓝色
    val accentColor = Color(0xFFF72585) // 粉色作为强调色
    val lightBackground = Color(0xFFF8F9FA) // 浅灰色背景
    val cardColor = Color.White // 卡片白色
    val textPrimary = Color(0xFF212529) // 主要文字颜色
    val textSecondary = Color(0xFF6C757D) // 次要文字颜色

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(lightBackground)
    ) {
        // 顶部栏 - 使用渐变背景
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(64.dp)
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(primaryColor, secondaryColor)
                    )
                )
                .padding(horizontal = 16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxSize(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "🏃‍♂️ 运动记录",
                    color = Color.White,
                    style = MaterialTheme.typography.titleLarge.copy(fontWeight = FontWeight.Bold),
                    modifier = Modifier.weight(1f)
                )

                // 添加统计信息
                Text(
                    text = "${exerciseRecords.size} 次",
                    color = Color.White.copy(alpha = 0.9f),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }

        // 进行中的运动
        currentExerciseRecord?.let { record ->
            OngoingExerciseCard(
                record = record,
                currentHeartRate = currentHeartRate,
                isDataAvailable = isDataAvailable,
                onEndExercise = { showEndExerciseDialog = true },
                primaryColor = primaryColor,
                accentColor = accentColor
            )
        }

        // 主要内容区域
        Column(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .padding(horizontal = 16.dp)
        ) {
            Spacer(modifier = Modifier.height(16.dp))

            if (exerciseRecords.isNotEmpty()) {
                // 添加标题和统计信息
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        text = "历史记录",
                        style = MaterialTheme.typography.titleMedium.copy(
                            fontWeight = FontWeight.Bold,
                            color = textPrimary
                        )
                    )

                    Text(
                        text = "共 ${exerciseRecords.size} 次",
                        style = MaterialTheme.typography.bodySmall.copy(color = textSecondary)
                    )
                }

                Spacer(modifier = Modifier.height(16.dp))

                LazyColumn(
                    modifier = Modifier.weight(1f),
                    verticalArrangement = Arrangement.spacedBy(12.dp)
                ) {
                    items(exerciseRecords) { record ->
                        ExerciseRecordItem(record = record, primaryColor = primaryColor)
                    }
                }
            } else {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(32.dp),
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.Center
                ) {
                    // 空状态图标背景
                    Box(
                        modifier = Modifier
                            .size(80.dp)
                            .background(
                                primaryColor.copy(alpha = 0.1f),
                                CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "🏃‍♂️",
                            style = MaterialTheme.typography.titleLarge
                        )
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                    Text(
                        text = "暂无运动记录",
                        style = MaterialTheme.typography.titleMedium.copy(
                            fontWeight = FontWeight.Bold,
                            color = textPrimary
                        )
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = "开始你的第一次运动吧",
                        style = MaterialTheme.typography.bodyMedium.copy(
                            color = textSecondary
                        ),
                        textAlign = TextAlign.Center
                    )
                }
            }
        }

        // 底部栏 - 使用卡片样式
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight()
                .shadow(
                    elevation = 8.dp,
                    shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
                )
                .background(cardColor)
                .padding(horizontal = 24.dp, vertical = 16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column {
                    Text(
                        text = "总运动次数",
                        style = MaterialTheme.typography.bodySmall.copy(color = textSecondary)
                    )
                    Text(
                        text = "${exerciseRecords.size} 次",
                        style = MaterialTheme.typography.titleMedium.copy(
                            fontWeight = FontWeight.Bold,
                            color = primaryColor
                        )
                    )
                }

                Button(
                    onClick = { showStartExerciseDialog = true },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = primaryColor,
                        contentColor = Color.White
                    ),
                    enabled = currentExerciseRecord == null,
                    modifier = Modifier
                        .height(48.dp)
                        .width(140.dp),
                    shape = RoundedCornerShape(12.dp),
                    elevation = ButtonDefaults.buttonElevation(
                        defaultElevation = 4.dp,
                        pressedElevation = 2.dp
                    )
                ) {
                    if (currentExerciseRecord == null) {
                        Icon(
                            imageVector = Icons.Outlined.PlayArrow,
                            contentDescription = "开始运动",
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("开始运动", fontWeight = FontWeight.Medium)
                    } else {
                        Icon(
                            painter = painterResource(R.drawable.run),
                            contentDescription = "运动中",
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("运动中", fontWeight = FontWeight.Medium)
                    }
                }
            }
        }
    }

    // 权限请求对话框
    if (showPermissionDialog) {
        PermissionRequestDialog(
            permissionStatus = permissionStatus!!,
            onGrantPermissions = {
                showPermissionDialog = false
                // 重新检查权限状态
                permissionStatus = healthDataManager.checkPermissions()
                if (permissionStatus!!.allGranted) {
                    // 权限已授予，重新初始化
                    coroutineScope.launch {
                        val initialized = healthDataManager.initialize()
                        if (initialized && !isAuthorized) {
                            val hasShownAuthBefore = sharedPrefs.getBoolean("has_shown_auth_dialog", false)
                            if (!hasShownAuthBefore) {
                                sharedPrefs.edit().putBoolean("has_shown_auth_dialog", true).apply()
                                showAuthorizationDialog = true
                            }
                        }
                    }
                }
            },
            onDismiss = {
                showPermissionDialog = false
            }
        )
    }

    // 华为健康服务授权对话框
    if (showAuthorizationDialog) {
        HuaweiAuthorizationDialog(
            isRequestingAuth = isRequestingAuth,
            onAuthorize = {
                isRequestingAuth = true
                coroutineScope.launch {
                    val authorized = healthDataManager.requestAuthorization()
                    isRequestingAuth = false
                    showAuthorizationDialog = false
                    // 无论授权成功与否，都不再显示授权对话框
                }
            },
            onDismiss = {
                showAuthorizationDialog = false
                // 用户取消授权，也不再显示授权对话框
            }
        )
    }

    // 开始运动对话框
    if (showStartExerciseDialog) {
        StartExerciseDialog(
            exerciseList = exerciseList,
            exerciseCategories = exerciseCategories,
            selectedCategory = selectedCategory,
            searchKeyword = searchKeyword,
            selectedExercise = selectedExercise,
            isLoadingExercises = isLoadingExercises,
            isStartingExercise = isStartingExercise,
            primaryColor = primaryColor,
            onCategoryChange = { category ->
                selectedCategory = category
                loadExercises(exerciseApiService, category, searchKeyword) { exercises ->
                    exerciseList = exercises
                }
            },
            onSearchChange = { keyword ->
                searchKeyword = keyword
                loadExercises(exerciseApiService, selectedCategory, keyword) { exercises ->
                    exerciseList = exercises
                }
            },
            onExerciseSelect = { exercise ->
                selectedExercise = exercise
            },
            onConfirm = {
                selectedExercise?.let { exercise ->
                    isStartingExercise = true
                    startExercise(
                        exerciseApiService,
                        ExerciseRecordStartRequest(
                            userId = currentUserId,
                            exerciseId = exercise.id,
                            startTime = getCurrentDateTime()
                        )
                    ) { success ->
                        isStartingExercise = false
                        if (success) {
                            // 重新检查进行中的运动
                            checkCurrentExercise(exerciseApiService, currentUserId) { record ->
                                currentExerciseRecord = record
                            }
                            showStartExerciseDialog = false
                        }
                    }
                }
            },
            onDismiss = { showStartExerciseDialog = false }
        )
    }

    // 结束运动对话框
    if (showEndExerciseDialog) {
        currentExerciseRecord?.let { record ->
            EndExerciseDialog(
                record = record,
                healthDataManager = healthDataManager,
                isEndingExercise = isEndingExercise,
                primaryColor = primaryColor,
                accentColor = accentColor,
                onConfirm = { endData ->
                    isEndingExercise = true
                    endExercise(
                        exerciseApiService,
                        record.id,
                        endData
                    ) { success ->
                        isEndingExercise = false
                        if (success) {
                            // 重新加载数据
                            checkCurrentExercise(
                                exerciseApiService,
                                currentUserId
                            ) { currentRecord ->
                                currentExerciseRecord = currentRecord
                            }
                            loadExerciseRecords(exerciseApiService, currentUserId) { records ->
                                exerciseRecords = records
                            }
                            showEndExerciseDialog = false
                        }
                    }
                },
                onDismiss = { showEndExerciseDialog = false }
            )
        }
    }
}

// 进行中的运动卡片
@Composable
fun OngoingExerciseCard(
    record: ExerciseRecordInfo,
    currentHeartRate: Int?,
    isDataAvailable: Boolean,
    onEndExercise: () -> Unit,
    primaryColor: Color,
    accentColor: Color
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp)
            .shadow(elevation = 8.dp, shape = RoundedCornerShape(16.dp)),
        colors = CardDefaults.cardColors(containerColor = Color.White),
        shape = RoundedCornerShape(16.dp),
        border = BorderStroke(1.dp, primaryColor.copy(alpha = 0.2f))
    ) {
        Column(
            modifier = Modifier.padding(20.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = "正在运动",
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = primaryColor,
                            fontWeight = FontWeight.Medium
                        )
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = record.exerciseName,
                        style = MaterialTheme.typography.titleLarge.copy(
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF212529)
                        )
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            painter = painterResource(R.drawable.schedule),
                            contentDescription = "开始时间",
                            modifier = Modifier.size(16.dp),
                            tint = Color(0xFF6C757D)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = formatDateTime(record.startTime),
                            style = MaterialTheme.typography.bodyMedium.copy(
                                color = Color(
                                    0xFF6C757D
                                )
                            )
                        )
                    }
                }

                // 实时心率显示
                if (isDataAvailable && currentHeartRate != null) {
                    Spacer(modifier = Modifier.height(12.dp))
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Favorite,
                            contentDescription = "实时心率",
                            modifier = Modifier.size(16.dp),
                            tint = Color(0xFFE91E63)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "实时心率: $currentHeartRate bpm",
                            style = MaterialTheme.typography.bodyMedium.copy(
                                color = Color(0xFFE91E63),
                                fontWeight = FontWeight.Medium
                            )
                        )
                    }
                } else if (!isDataAvailable) {
                    Spacer(modifier = Modifier.height(12.dp))
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Filled.Favorite,
                            contentDescription = "心率数据",
                            modifier = Modifier.size(16.dp),
                            tint = Color.Gray
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "正在获取心率数据...",
                            style = MaterialTheme.typography.bodyMedium.copy(
                                color = Color.Gray
                            )
                        )
                    }
                }

                Button(
                    onClick = onEndExercise,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = accentColor,
                        contentColor = Color.White
                    ),
                    modifier = Modifier
                        .height(40.dp)
                        .width(40.dp),
                    shape = CircleShape,
                    elevation = ButtonDefaults.buttonElevation(
                        defaultElevation = 4.dp,
                        pressedElevation = 2.dp
                    )
                ) {
                    Icon(
                        imageVector = Icons.Default.Stop,
                        contentDescription = "结束运动",
                        modifier = Modifier.size(20.dp)
                    )
                }
            }

            // 添加进度指示器
            Spacer(modifier = Modifier.height(16.dp))
            LinearProgressIndicator(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(6.dp)
                    .clip(RoundedCornerShape(3.dp)),
                progress = { 0.7f }, // 模拟进度
                color = primaryColor,
                trackColor = primaryColor.copy(alpha = 0.2f)
            )
        }
    }
}

// 运动记录项组件
@Composable
fun ExerciseRecordItem(record: ExerciseRecordInfo, primaryColor: Color) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .shadow(elevation = 2.dp, shape = RoundedCornerShape(12.dp)),
        colors = CardDefaults.cardColors(containerColor = Color.White),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = record.exerciseName,
                        style = MaterialTheme.typography.bodyLarge.copy(
                            fontWeight = FontWeight.Bold,
                            color = Color(0xFF212529)
                        )
                    )
                    Spacer(modifier = Modifier.height(8.dp))

                    // 运动数据
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        if (record.duration != null) {
                            DataChip(
                                icon = Icons.Outlined.Schedule,
                                value = record.duration,
                                color = primaryColor
                            )
                        }
                        if (record.avgHeartRate != null) {
                            DataChip(
                                icon = Icons.Outlined.Favorite,
                                value = "${record.avgHeartRate.toInt()} bpm",
                                color = Color(0xFFE91E63)
                            )
                        }
                        if (record.avgSpeed != null) {
                            DataChip(
                                icon = Icons.Outlined.Speed,
                                value = "${record.avgSpeed} km/h",
                                color = Color(0xFF2196F3)
                            )
                        }
                    }
                }

                Text(
                    text = formatDateTime(record.startTime),
                    style = MaterialTheme.typography.bodySmall.copy(color = Color(0xFF6C757D))
                )
            }
        }
    }
}

// 数据芯片组件
@Composable
fun DataChip(icon: ImageVector, value: String, color: Color) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.padding(vertical = 4.dp)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            modifier = Modifier.size(14.dp),
            tint = color
        )
        Spacer(modifier = Modifier.width(4.dp))
        Text(
            text = value,
            style = MaterialTheme.typography.bodySmall.copy(
                color = Color(0xFF6C757D),
                fontWeight = FontWeight.Medium
            )
        )
    }
}

// 开始运动对话框
@Composable
fun StartExerciseDialog(
    exerciseList: List<ExerciseInfo>,
    exerciseCategories: List<String>,
    selectedCategory: String,
    searchKeyword: String,
    selectedExercise: ExerciseInfo?,
    isLoadingExercises: Boolean,
    isStartingExercise: Boolean,
    primaryColor: Color,
    onCategoryChange: (String) -> Unit,
    onSearchChange: (String) -> Unit,
    onExerciseSelect: (ExerciseInfo) -> Unit,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    Dialog(
        onDismissRequest = onDismiss
    ) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            shape = RoundedCornerShape(20.dp),
            color = Color.White
        ) {
            Column(
                modifier = Modifier.padding(24.dp)
            ) {
                // 标题
                Text(
                    text = "选择运动",
                    style = MaterialTheme.typography.titleLarge.copy(
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF212529)
                    ),
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 搜索框
                OutlinedTextField(
                    value = searchKeyword,
                    onValueChange = onSearchChange,
                    label = { Text("搜索运动", color = Color(0xFF6C757D)) },
                    leadingIcon = {
                        Icon(Icons.Outlined.Search, contentDescription = "搜索")
                    },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth(),
                    shape = RoundedCornerShape(12.dp)
                )

                Spacer(modifier = Modifier.height(16.dp))

                // 分类选择
                if (exerciseCategories.isNotEmpty()) {
                    LazyRow(
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        items(listOf("全部分类") + exerciseCategories) { category ->
                            FilterChip(
                                selected = selectedCategory == category,
                                onClick = { onCategoryChange(category) },
                                label = {
                                    Text(category, style = MaterialTheme.typography.bodyMedium)
                                },
                                colors = FilterChipDefaults.filterChipColors(
                                    selectedContainerColor = primaryColor,
                                    selectedLabelColor = Color.White,
                                    containerColor = Color(0xFFF8F9FA),
                                    labelColor = Color(0xFF6C757D)
                                )
                            )
                        }
                    }
                    Spacer(modifier = Modifier.height(16.dp))
                }

                // 运动列表
                if (isLoadingExercises) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(color = primaryColor)
                    }
                } else if (exerciseList.isNotEmpty()) {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp)
                    ) {
                        items(exerciseList) { exercise ->
                            ExerciseSelectionItem(
                                exercise = exercise,
                                isSelected = selectedExercise?.id == exercise.id,
                                primaryColor = primaryColor,
                                onClick = { onExerciseSelect(exercise) }
                            )
                        }
                    }
                } else {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(200.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = "暂无运动项目",
                            color = Color(0xFF6C757D)
                        )
                    }
                }

                Spacer(modifier = Modifier.height(24.dp))

                // 按钮区域
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(
                        onClick = onDismiss,
                        colors = ButtonDefaults.textButtonColors(
                            contentColor = Color(0xFF6C757D)
                        )
                    ) {
                        Text("取消")
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    Button(
                        onClick = onConfirm,
                        enabled = selectedExercise != null && !isStartingExercise,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = primaryColor,
                            contentColor = Color.White
                        ),
                        modifier = Modifier.height(40.dp),
                        shape = RoundedCornerShape(10.dp)
                    ) {
                        if (isStartingExercise) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                color = Color.White,
                                strokeWidth = 2.dp
                            )
                        } else {
                            Icon(
                                imageVector = Icons.Outlined.PlayArrow,
                                contentDescription = "开始运动",
                                modifier = Modifier.size(18.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text("开始运动", fontWeight = FontWeight.Medium)
                        }
                    }
                }
            }
        }
    }
}

// 结束运动对话框
@Composable
fun EndExerciseDialog(
    record: ExerciseRecordInfo,
    healthDataManager: HealthDataManager,
    isEndingExercise: Boolean,
    primaryColor: Color,
    accentColor: Color,
    onConfirm: (ExerciseRecordEndRequest) -> Unit,
    onDismiss: () -> Unit
) {
    // 使用华为手表真实数据
    var avgHeartRate by remember { mutableStateOf<Double?>(null) }
    var maxHeartRate by remember { mutableStateOf<Double?>(null) }
    var avgSpeed by remember { mutableStateOf<Double?>(null) }
    var maxSpeed by remember { mutableStateOf<Double?>(null) }
    var isLoadingData by remember { mutableStateOf(true) }
    
    val coroutineScope = rememberCoroutineScope()
    
    // 获取华为手表数据
    LaunchedEffect(record) {
        isLoadingData = true
        try {
            val startTime = System.currentTimeMillis() - (30 * 60 * 1000) // 假设运动30分钟
            val endTime = System.currentTimeMillis()
            
            // 并行获取所有数据
            val avgHeartRateResult = healthDataManager.getAverageHeartRate(startTime, endTime)
            val maxHeartRateResult = healthDataManager.getMaxHeartRate(startTime, endTime)
            val avgSpeedResult = healthDataManager.getAverageSpeed(startTime, endTime)
            
            avgHeartRateResult.fold(
                onSuccess = { avgHeartRate = it },
                onFailure = { 
                    // 如果获取失败，使用模拟数据
                    avgHeartRate = Random.nextDouble(80.0, 140.0)
                }
            )
            
            maxHeartRateResult.fold(
                onSuccess = { maxHeartRate = it },
                onFailure = { 
                    maxHeartRate = Random.nextDouble(140.0, 180.0)
                }
            )
            
            avgSpeedResult.fold(
                onSuccess = { avgSpeed = it },
                onFailure = { 
                    avgSpeed = if (record.hasSpeed) Random.nextDouble(5.0, 15.0) else null
                }
            )
            
            maxSpeed = avgSpeed?.let { it + 5.0 }
            
        } catch (e: Exception) {
            // 发生异常时使用模拟数据
            avgHeartRate = Random.nextDouble(80.0, 140.0)
            maxHeartRate = Random.nextDouble(140.0, 180.0)
            avgSpeed = if (record.hasSpeed) Random.nextDouble(5.0, 15.0) else null
            maxSpeed = avgSpeed?.let { it + 5.0 }
        } finally {
            isLoadingData = false
        }
    }

    Dialog(
        onDismissRequest = onDismiss
    ) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            shape = RoundedCornerShape(20.dp),
            color = Color.White
        ) {
            Column(
                modifier = Modifier.padding(24.dp)
            ) {
                // 标题
                Text(
                    text = "结束运动",
                    style = MaterialTheme.typography.titleLarge.copy(
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF212529)
                    ),
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 运动信息
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(bottom = 16.dp)
                ) {
                    Icon(
                        painter = painterResource(R.drawable.run),
                        contentDescription = "运动",
                        tint = primaryColor,
                        modifier = Modifier.size(24.dp)
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Text(
                        text = record.exerciseName,
                        style = MaterialTheme.typography.bodyLarge.copy(
                            fontWeight = FontWeight.Medium
                        )
                    )
                }

                // 数据卡片
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 8.dp),
                    colors = CardDefaults.cardColors(containerColor = Color(0xFFF8F9FA)),
                    shape = RoundedCornerShape(12.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        if (isLoadingData) {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .height(100.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally
                                ) {
                                    CircularProgressIndicator(
                                        color = primaryColor,
                                        modifier = Modifier.size(32.dp)
                                    )
                                    Spacer(modifier = Modifier.height(8.dp))
                                    Text(
                                        text = "正在获取华为手表数据...",
                                        style = MaterialTheme.typography.bodyMedium.copy(
                                            color = Color(0xFF6C757D)
                                        )
                                    )
                                }
                            }
                        } else {
                            if (record.hasHeartRate && avgHeartRate != null && maxHeartRate != null) {
                                DataRow(
                                    icon = Icons.Outlined.Favorite,
                                    title = "心率数据 (华为手表)",
                                    items = listOf(
                                        "平均心率: ${avgHeartRate?.toInt() ?: 0} bpm" to Color(0xFFE91E63),
                                        "最大心率: ${maxHeartRate?.toInt() ?: 0} bpm" to Color(0xFFC2185B)
                                    )
                                )
                                if (record.hasSpeed) Spacer(modifier = Modifier.height(12.dp))
                            }

                            if (record.hasSpeed && avgSpeed != null && maxSpeed != null) {
                                DataRow(
                                    icon = Icons.Outlined.Speed,
                                    title = "速度数据 (华为手表)",
                                    items = listOf(
                                        "平均速度: ${String.format("%.1f", avgSpeed)} km/h" to Color(
                                            0xFF2196F3
                                        ),
                                        "最大速度: ${String.format("%.1f", maxSpeed)} km/h" to Color(
                                            0xFF1976D2
                                        )
                                    )
                                )
                            }
                        }
                    }
                }

                Text(
                    text = if (isLoadingData) "正在获取华为手表数据..." else "数据来源：华为手表",
                    style = MaterialTheme.typography.bodySmall.copy(color = Color(0xFF6C757D)),
                    modifier = Modifier.padding(vertical = 8.dp)
                )

                Spacer(modifier = Modifier.height(16.dp))

                // 按钮区域
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(
                        onClick = onDismiss,
                        colors = ButtonDefaults.textButtonColors(
                            contentColor = Color(0xFF6C757D)
                        )
                    ) {
                        Text("取消")
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    Button(
                        onClick = {
                            val endData = ExerciseRecordEndRequest(
                                avgHeartRate = avgHeartRate ?: Random.nextDouble(80.0, 140.0),
                                maxHeartRate = maxHeartRate ?: Random.nextDouble(140.0, 180.0),
                                avgSpeed = avgSpeed,
                                maxSpeed = maxSpeed
                            )
                            onConfirm(endData)
                        },
                        enabled = !isEndingExercise && !isLoadingData,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = accentColor,
                            contentColor = Color.White
                        ),
                        modifier = Modifier.height(40.dp),
                        shape = RoundedCornerShape(10.dp)
                    ) {
                        if (isEndingExercise) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                color = Color.White,
                                strokeWidth = 2.dp
                            )
                        } else {
                            Icon(
                                imageVector = Icons.Outlined.Stop,
                                contentDescription = "结束运动",
                                modifier = Modifier.size(18.dp)
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text("结束运动", fontWeight = FontWeight.Medium)
                        }
                    }
                }
            }
        }
    }
}

// 数据行组件
@Composable
fun DataRow(icon: ImageVector, title: String, items: List<Pair<String, Color>>) {
    Column {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.padding(bottom = 8.dp)
        ) {
            Icon(
                imageVector = icon,
                contentDescription = title,
                modifier = Modifier.size(16.dp),
                tint = Color(0xFF6C757D)
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text(
                text = title,
                style = MaterialTheme.typography.bodyMedium.copy(
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF6C757D)
                )
            )
        }
        Column(
            verticalArrangement = Arrangement.spacedBy(4.dp)
        ) {
            items.forEach { (text, color) ->
                Text(
                    text = text,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        fontWeight = FontWeight.Medium,
                        color = color
                    )
                )
            }
        }
    }
}

// 运动选择项组件
@Composable
fun ExerciseSelectionItem(
    exercise: ExerciseInfo,
    isSelected: Boolean,
    primaryColor: Color,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = if (isSelected) primaryColor.copy(alpha = 0.1f) else Color.White
        ),
        shape = RoundedCornerShape(12.dp),
        border = if (isSelected) BorderStroke(1.dp, primaryColor) else null
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = exercise.name,
                    style = MaterialTheme.typography.bodyMedium.copy(
                        fontWeight = FontWeight.Medium,
                        color = if (isSelected) primaryColor else Color(0xFF212529)
                    )
                )
                if (exercise.description.isNotBlank()) {
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = exercise.description,
                        style = MaterialTheme.typography.bodySmall.copy(
                            color = if (isSelected) primaryColor.copy(alpha = 0.8f) else Color(
                                0xFF6C757D
                            )
                        ),
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
            if (isSelected) {
                Icon(
                    imageVector = Icons.Default.CheckCircle,
                    contentDescription = "已选择",
                    tint = primaryColor,
                    modifier = Modifier.size(20.dp)
                )
            }
        }
    }
}

// 辅助函数
fun getCurrentDateTime(): String {
    val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
    return sdf.format(Date())
}

fun formatDateTime(dateTimeString: String): String {
    return try {
        val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())
        val outputFormat = SimpleDateFormat("MM-dd HH:mm", Locale.getDefault())
        val date = inputFormat.parse(dateTimeString)
        outputFormat.format(date ?: Date())
    } catch (e: Exception) {
        dateTimeString
    }
}

// 加载运动列表
fun loadExercises(
    exerciseApiService: ExerciseApiService,
    category: String,
    keyword: String,
    onResult: (List<ExerciseInfo>) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        val result = if (keyword.isNotBlank()) {
            exerciseApiService.searchExercises(keyword)
        } else if (category != "全部分类") {
            exerciseApiService.getExercisesByCategory(category)
        } else {
            exerciseApiService.getAllExercises()
        }

        result.fold(
            onSuccess = { exercises ->
                onResult(exercises)
            },
            onFailure = {
                onResult(emptyList())
            }
        )
    }
}

// 加载运动记录
fun loadExerciseRecords(
    exerciseApiService: ExerciseApiService,
    userId: Long,
    onResult: (List<ExerciseRecordInfo>) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        exerciseApiService.getExerciseRecordsByUserId(userId).fold(
            onSuccess = { records ->
                onResult(records)
            },
            onFailure = {
                onResult(emptyList())
            }
        )
    }
}

// 检查进行中的运动
fun checkCurrentExercise(
    exerciseApiService: ExerciseApiService,
    userId: Long,
    onResult: (ExerciseRecordInfo?) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        exerciseApiService.getExerciseRecordsByUserIdAndStatus(userId, "进行中").fold(
            onSuccess = { records ->
                onResult(records.firstOrNull())
            },
            onFailure = {
                onResult(null)
            }
        )
    }
}

// 开始运动
fun startExercise(
    exerciseApiService: ExerciseApiService,
    request: ExerciseRecordStartRequest,
    onResult: (Boolean) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        exerciseApiService.startExercise(request).fold(
            onSuccess = {
                onResult(true)
            },
            onFailure = {
                onResult(false)
            }
        )
    }
}

// 结束运动
fun endExercise(
    exerciseApiService: ExerciseApiService,
    recordId: Long,
    endData: ExerciseRecordEndRequest,
    onResult: (Boolean) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        exerciseApiService.endExercise(recordId, endData).fold(
            onSuccess = {
                onResult(true)
            },
            onFailure = {
                onResult(false)
            }
        )
    }
}

// 加载运动分类
fun loadExerciseCategories(
    exerciseApiService: ExerciseApiService,
    onResult: (List<String>) -> Unit
) {
    CoroutineScope(Dispatchers.IO).launch {
        exerciseApiService.getExerciseCategories().fold(
            onSuccess = { categories ->
                onResult(categories)
            },
            onFailure = {
                onResult(emptyList())
            }
        )
    }
}
// 权限请求对话框
@Composable
fun PermissionRequestDialog(
    permissionStatus: PermissionStatus,
    onGrantPermissions: () -> Unit,
    onDismiss: () -> Unit
) {
    Dialog(
        onDismissRequest = onDismiss
    ) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            shape = RoundedCornerShape(20.dp),
            color = Color.White
        ) {
            Column(
                modifier = Modifier.padding(24.dp)
            ) {
                // 标题
                Text(
                    text = "需要权限",
                    style = MaterialTheme.typography.titleLarge.copy(
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF212529)
                    ),
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 权限说明
                Text(
                    text = "为了获取华为手表的健康数据，需要以下权限：",
                    style = MaterialTheme.typography.bodyMedium.copy(
                        color = Color(0xFF6C757D)
                    ),
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 权限列表
                Column(
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    if (!permissionStatus.bluetoothGranted) {
                        PermissionItem(
                            icon = Icons.Filled.Bluetooth,
                            title = "蓝牙权限",
                            description = "连接华为手表"
                        )
                    }
                    if (!permissionStatus.locationGranted) {
                        PermissionItem(
                            icon = Icons.Filled.LocationOn,
                            title = "位置权限",
                            description = "获取运动轨迹"
                        )
                    }
                    if (!permissionStatus.bodySensorsGranted) {
                        PermissionItem(
                            icon = Icons.Filled.Favorite,
                            title = "身体传感器权限",
                            description = "获取心率等健康数据"
                        )
                    }
                    if (!permissionStatus.activityRecognitionGranted) {
                        PermissionItem(
                            icon = Icons.Filled.DirectionsRun,
                            title = "活动识别权限",
                            description = "监测运动状态"
                        )
                    }
                }

                Spacer(modifier = Modifier.height(24.dp))

                // 按钮区域
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(
                        onClick = onDismiss,
                        colors = ButtonDefaults.textButtonColors(
                            contentColor = Color(0xFF6C757D)
                        )
                    ) {
                        Text("取消")
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    Button(
                        onClick = onGrantPermissions,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFF4361EE),
                            contentColor = Color.White
                        ),
                        modifier = Modifier.height(40.dp),
                        shape = RoundedCornerShape(10.dp)
                    ) {
                        Text("授予权限", fontWeight = FontWeight.Medium)
                    }
                }
            }
        }
    }
}

// 权限项组件
@Composable
fun PermissionItem(
    icon: ImageVector,
    title: String,
    description: String
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.fillMaxWidth()
    ) {
        Icon(
            imageVector = icon,
            contentDescription = title,
            modifier = Modifier.size(20.dp),
            tint = Color(0xFF4361EE)
        )
        Spacer(modifier = Modifier.width(12.dp))
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = title,
                style = MaterialTheme.typography.bodyMedium.copy(
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF212529)
                )
            )
            Text(
                text = description,
                style = MaterialTheme.typography.bodySmall.copy(
                    color = Color(0xFF6C757D)
                )
            )
        }
    }
}

// 华为健康服务授权对话框
@Composable
fun HuaweiAuthorizationDialog(
    isRequestingAuth: Boolean,
    onAuthorize: () -> Unit,
    onDismiss: () -> Unit
) {
    Dialog(
        onDismissRequest = onDismiss
    ) {
        Surface(
            modifier = Modifier
                .fillMaxWidth()
                .wrapContentHeight(),
            shape = RoundedCornerShape(20.dp),
            color = Color.White
        ) {
            Column(
                modifier = Modifier.padding(24.dp)
            ) {
                // 标题
                Text(
                    text = "华为健康服务授权",
                    style = MaterialTheme.typography.titleLarge.copy(
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF212529)
                    ),
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 说明文本
                Text(
                    text = "需要授权访问华为健康服务来获取手表的健康数据，包括心率、速度、步数等信息。",
                    style = MaterialTheme.typography.bodyMedium.copy(
                        color = Color(0xFF6C757D)
                    ),
                    modifier = Modifier.padding(bottom = 16.dp)
                )

                // 功能列表
                Column(
                    verticalArrangement = Arrangement.spacedBy(8.dp),
                    modifier = Modifier.padding(bottom = 24.dp)
                ) {
                    FeatureItem(
                        icon = Icons.Filled.Favorite,
                        title = "实时心率监测",
                        description = "运动期间实时显示心率数据"
                    )
                    FeatureItem(
                        icon = Icons.Outlined.Speed,
                        title = "运动数据记录",
                        description = "记录速度、步数、距离等运动数据"
                    )
                    FeatureItem(
                        icon = Icons.Filled.Analytics,
                        title = "数据分析",
                        description = "提供详细的运动数据分析"
                    )
                }

                // 按钮区域
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextButton(
                        onClick = onDismiss,
                        colors = ButtonDefaults.textButtonColors(
                            contentColor = Color(0xFF6C757D)
                        )
                    ) {
                        Text("取消")
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    Button(
                        onClick = onAuthorize,
                        enabled = !isRequestingAuth,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = Color(0xFFE91E63),
                            contentColor = Color.White
                        ),
                        modifier = Modifier.height(40.dp),
                        shape = RoundedCornerShape(10.dp)
                    ) {
                        if (isRequestingAuth) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                color = Color.White,
                                strokeWidth = 2.dp
                            )
                        } else {
                            Text("授权", fontWeight = FontWeight.Medium)
                        }
                    }
                }
            }
        }
    }
}

// 功能项组件
@Composable
fun FeatureItem(
    icon: ImageVector,
    title: String,
    description: String
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.fillMaxWidth()
    ) {
        Icon(
            imageVector = icon,
            contentDescription = title,
            modifier = Modifier.size(20.dp),
            tint = Color(0xFFE91E63)
        )
        Spacer(modifier = Modifier.width(12.dp))
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = title,
                style = MaterialTheme.typography.bodyMedium.copy(
                    fontWeight = FontWeight.Medium,
                    color = Color(0xFF212529)
                )
            )
            Text(
                text = description,
                style = MaterialTheme.typography.bodySmall.copy(
                    color = Color(0xFF6C757D)
                )
            )
        }
    }
}

